package com.flowplan.auth.service;

import com.flowplan.auth.dto.LoginResponse;
import com.flowplan.auth.repository.SysUserRepository;
import com.flowplan.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户信息服务类
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Service
public class UserService {
    
    @Autowired
    private SysUserRepository userRepository;
    
    /**
     * 根据用户ID获取用户信息（带缓存）
     * 
     * @param userId 用户ID
     * @return 用户信息
     */
    @Cacheable(value = "users", key = "#userId")
    @Transactional(readOnly = true)
    public LoginResponse.UserInfo getUserInfoById(Long userId) {
        log.debug("从数据库获取用户信息: userId={}", userId);
        
        SysUser user = userRepository.findById(userId)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + userId));
        
        if (!user.getIsActive()) {
            throw new UsernameNotFoundException("用户已被禁用: " + userId);
        }
        
        return LoginResponse.UserInfo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .role(user.getRole().getDescription())
                .orgName(user.getOrg() != null ? user.getOrg().getOrgName() : null)
                .avatarUrl(user.getAvatarUrl())
                .build();
    }
    
    /**
     * 根据用户名获取用户信息（带缓存）
     * 
     * @param username 用户名
     * @return 用户信息
     */
    @Cacheable(value = "users", key = "#username")
    @Transactional(readOnly = true)
    public LoginResponse.UserInfo getUserInfoByUsername(String username) {
        log.debug("从数据库获取用户信息: username={}", username);
        
        SysUser user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
        
        if (!user.getIsActive()) {
            throw new UsernameNotFoundException("用户已被禁用: " + username);
        }
        
        return LoginResponse.UserInfo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .role(user.getRole().getDescription())
                .orgName(user.getOrg() != null ? user.getOrg().getOrgName() : null)
                .avatarUrl(user.getAvatarUrl())
                .build();
    }
}